<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px)">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" inline label-position="left" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="会员ID" prop="id">
                  <el-input v-model="queryParams.id" placeholder="请输入会员ID" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="推荐人ID" prop="parentId">
                  <el-input v-model="queryParams.parentId" placeholder="请输入推荐人的ID" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="层级" prop="level">
                  <el-input-number v-model="queryParams.params.minLevel" placeholder="最小层级" clearable :min="0"
                    @keyup.enter="handleQuery" />
                  <span class="mx-2">至</span>
                  <el-input-number v-model="queryParams.params.maxLevel" placeholder="最大层级" clearable :min="0"
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="直推人数" prop="directReferralsCount">
                  <el-input-number v-model="queryParams.params.minReferralsCount" placeholder="最少人数" clearable :min="0"
                    @keyup.enter="handleQuery" />
                  <span class="mx-2">至</span>
                  <el-input-number v-model="queryParams.params.maxReferralsCount" placeholder="最多人数" clearable :min="0"
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="伞下人数" prop="downlineMembersCount">
                  <el-input-number v-model="queryParams.params.minMembersCount" placeholder="最少人数" clearable :min="0"
                    @keyup.enter="handleQuery" />
                  <span class="mx-2">至</span>
                  <el-input-number v-model="queryParams.params.maxMembersCount" placeholder="最少人数" clearable :min="0"
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="推荐深度" prop="referralDepth">
                  <el-input-number v-model="queryParams.params.minDepth" placeholder="最小深度" clearable :min="0"
                    @keyup.enter="handleQuery" />
                  <span class="mx-2">至</span>
                  <el-input-number v-model="queryParams.params.maxDepth" placeholder="最大深度" clearable :min="0"
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="排序字段" prop="sortField">
                  <el-select v-model="queryParams.sortField" placeholder="请选择排序字段" clearable>
                    <el-option v-for="dict in sktj_sort_field" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="排序方式" prop="ascOrDesc">
                  <el-select v-model="queryParams.ascOrDesc" placeholder="请选择排序方式" clearable>
                    <el-option v-for="dict in sktj_asc_desc" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24" :offset="20">
                <el-form-item label-width="0">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>


    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['numberLevelInfo:numberLevelInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['numberLevelInfo:numberLevelInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="danger">
                删除
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-dropdown-item>
                  <el-dropdown-item icon="Delete" @click="handleDeleteAll()"> 全部删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                导出
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="handleExport">全部导出</el-dropdown-item>
                  <el-dropdown-item icon="Download" :disabled="multiple" @click="handleExportByIds()">
                    选择导出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="RefreshRight" @click="handleRegenerate"
              v-hasPermi="['numberLevelInfo:numberLevelInfo:generate']">重新生成</el-button>
          </el-col>

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="numberlevelinfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column  v-if="hasData('id') && true" label="会员ID" align="center" prop="id"/>
        <el-table-column  v-if="hasData('parentId')" label="推荐人ID" align="center" prop="parentId"  width="180"/>
        <el-table-column  v-if="hasData('level')" label="层级" align="center" prop="level" />
        <el-table-column  v-if="hasData('directReferralsCount')" label="直推人数" align="center" prop="directReferralsCount" />
        <el-table-column  v-if="hasData('downlineMembersCount')" label="伞下人数" align="center" prop="downlineMembersCount" />
        <el-table-column  v-if="hasData('referralDepth')" label="推荐深度" align="center" prop="referralDepth" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['numberLevelInfo:numberLevelInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['numberLevelInfo:numberLevelInfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改层级信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="numberlevelinfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员ID" prop="id">
          <el-input v-model="form.id" placeholder="请输入会员ID" />
        </el-form-item>
        <el-form-item label="推荐人ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入推荐人ID"  />
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-input v-model="form.level" placeholder="请输入层级" />
        </el-form-item>
        <el-form-item label="直推人数" prop="directReferralsCount">
          <el-input v-model="form.directReferralsCount" placeholder="请输入直推人数" />
        </el-form-item>
        <el-form-item label="伞下人数" prop="downlineMembersCount">
          <el-input v-model="form.downlineMembersCount" placeholder="请输入伞下人数" />
        </el-form-item>
        <el-form-item label="推荐深度" prop="referralDepth">
          <el-input v-model="form.referralDepth" placeholder="请输入推荐深度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Numberlevelinfo" lang="ts">
import { listNumberlevelinfo, getNumberlevelinfo, delNumberlevelinfo, addNumberlevelinfo, updateNumberlevelinfo, regenerateLevelInfo ,exportSelectedLevelInfo,clearNumberlevelinfo} from '@/api/numberlevelinfo/numberlevelinfo';
import { NumberlevelinfoVO, NumberlevelinfoQuery, NumberlevelinfoForm } from '@/api/numberlevelinfo/numberlevelinfo/types';




const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sktj_sort_field, sktj_asc_desc } = toRefs<any>(proxy?.useDict( 'sktj_sort_field', 'sktj_asc_desc'));
const numberlevelinfoList = ref<NumberlevelinfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const numberlevelinfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: NumberlevelinfoForm = {
  id: undefined,
  parentId: undefined,
  level: undefined,
  directReferralsCount: undefined,
  downlineMembersCount: undefined,
  referralDepth: undefined,
}
const data = reactive<PageData<NumberlevelinfoForm, NumberlevelinfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    parentId: undefined,
    level: undefined,
    directReferralsCount: undefined,
    downlineMembersCount: undefined,
    referralDepth: undefined,
    sortField: undefined,
    ascOrDesc: undefined,
    params: {
      minLevel: undefined,
      maxLevel: undefined,
      maxReferralsCount: undefined,
      minReferralsCount: undefined,
      maxMembersCount: undefined,
      minMembersCount: undefined,
      maxDepth: undefined,
      minDepth: undefined,
    }
  },
  rules: {
    id: [
      { required: true, message: "会员id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询层级信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNumberlevelinfo(queryParams.value);
  numberlevelinfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  numberlevelinfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
    // 手动重置嵌套的 params 对象
  queryParams.value.params = {
    minLevel: undefined,
    maxLevel: undefined,
    maxReferralsCount: undefined,
    minReferralsCount: undefined,
    maxMembersCount: undefined,
    minMembersCount: undefined,
    maxDepth: undefined,
    minDepth: undefined,
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: NumberlevelinfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const isAddOperation = ref(false); // 新增标志位
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加层级信息";
  isAddOperation.value = true; // 设置新增标志位
}

/** 修改按钮操作 */
const handleUpdate = async (row?: NumberlevelinfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getNumberlevelinfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改层级信息";
  isAddOperation.value = false; // 设置修改标志位
}


/** 提交按钮 */
const submitForm = () => {
  numberlevelinfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (isAddOperation.value) {
        // 如果是新增操作
        await addNumberlevelinfo(form.value).finally(() => buttonLoading.value = false);
      } else {
        // 如果是修改操作
        await updateNumberlevelinfo(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
};


/** 删除按钮操作 */
const handleDelete = async (row?: NumberlevelinfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除层级信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delNumberlevelinfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('numberLevelInfo/numberLevelInfo/export', {
    ...queryParams.value
  }, `numberlevelinfo_${new Date().getTime()}.xlsx`)
}


// 定义一个 sleep 函数
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));



// 重新生成层级数据
const handleRegenerate = async () => {
  let loadingInstance;
  try {
    // 弹窗二次确认
    await proxy?.$modal.confirm('确定要重新生成层级信息吗').finally(() => loading.value = false);

    // 显示加载提示
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在重新生成层级数据，请稍等..............',
      background: 'rgba(0, 0, 0, 0.7)',
    });

    console.log('开始等待'); // 添加日志
    await sleep(1000);
    console.log('等待结束，开始调用API'); // 添加日志

    // 调用API
    const response = await regenerateLevelInfo();
   // console.log('API Response:', response); // 添加日志

    // 显示成功提示
    ElMessage.success('层级信息重新生成成功');

    // 刷新列表
    getList();

  } catch (error) {
    console.error('重新生成层级信息时出错:', error);
   // ElMessage.error('重新生成层级信息失败，请重试');
  } finally {
    loadingInstance.close();
    loading.value = false;
  }
}

/**检查列中是否有数据，如果没有则隐藏该列 */
const checkColumn = (row: NumberlevelinfoVO, column: any) => {
  return row[column.property] ? true : false;
}
const hasData = (prop: string) => {
  // 检查中的至少一条数据是否包含prop属性且该属性有值
  return numberlevelinfoList.value.some(item => item[prop] && item[prop] !== '');
};

/** 导出选中按钮操作 */
const handleExportByIds = async (row?: NumberlevelinfoVO) => {
  try {
    const _ids = Array.isArray(row?.id) ? row?.id : Array.isArray(ids.value) ? ids.value : [];
    // 确保有数据被选中
    if (_ids.length === 0) {
      ElMessage.warning('请至少选择一项进行导出');
      return;
    }

    // 调用后端API进行导出操作，直接处理返回的Blob对象
    const response = await exportSelectedLevelInfo(_ids);

    // 由于后端直接返回了Blob，我们可以直接处理这个Blob来下载文件
    //const url = window.URL.createObjectURL(new Blob([response]));
    const url = window.URL.createObjectURL(response as unknown as Blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `numberDeposits_${new Date().getTime()}.xlsx`); // 自定义文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出选中数据时发生错误:', error);
    ElMessage.error('导出过程中发生错误，请检查网络或联系管理员');
  }
};

/**清空表数据 */
const handleDeleteAll = async () => {
  try {
      // 确认操作
      await proxy?.$modal.confirm('确定要清空表数据吗');
      // 开始清理并加载列表
      loading.value = true;
      await clearNumberlevelinfo();
      proxy?.$modal.msgSuccess("清空数据成功");
      getList();
    } catch (error) {
      // 捕获到错误时，关闭加载状态并给出错误提示
      loading.value = false;
      console.error("操作失败", error);
      //ElMessage.error("操作失败，请稍后重试");
    } finally {
      // 确保loading状态被正确关闭
      loading.value = false;
    }
}



onMounted(() => {
  getList();
});
</script>
